<template>
    <n-scrollbar class="tab-scroller">
        <div class="quick-start-bar">
            参考配置：
            <n-space style="gap: 0 4px">
                <n-tag
                    class="quick-item"
                    size="small"
                    @click="compControl.com_modal_samba_sample.show = !compControl.com_modal_samba_sample.show">
                    参考1
                </n-tag>
            </n-space>
        </div>
        <n-code
            v-if="!compControl.edit_control.edit_mode"
            :code="display_text"
            language="shell"
            show-line-numbers />
        <n-input
            v-else
            autosize
            class="tab-scroller"
            v-model:value="display_text"
            type="textarea"
            placeholder="基本的 Textarea" />
    </n-scrollbar>
    <div id="com_modal_samba_sample" class="quick-item-modal-card quick-item-modal-nomodal">
        <n-modal
            to="#com_modal_samba_sample"
            v-model:show="compControl.com_modal_samba_sample.show"
            :mask-closable="false"
            title="参考配置"
            preset="card"
            draggable
            :trap-focus="false"
            :style="{ maxWidth: '600px' }">
            <div style="">
                <n-code language="js" :code="compControl.com_modal_samba_sample.data" class="quick-code" />
            </div>
        </n-modal>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { useDialog, useMessage,  } from 'naive-ui' 
import type { AxiosResponse } from 'axios'
import { axg_getConfigFile, axp_editConfigFile } from './conf-interface' 

const route = useRoute()
const dialog = useDialog()
const message = useMessage()

const display_text = ref('')
const display_text_backup = ref('')

const compControl = reactive({
    edit_control: {
        edit_mode: false,
        computed_edited: computed<boolean>((): boolean => {
            return Boolean(display_text.value != display_text_backup.value)
        }),
        handleStartEdit() {
            compControl.edit_control.edit_mode = true
        },
        async handleEndEdit(save: boolean = false): Promise<boolean> {
            if (save) {
                const response: AxiosResponse = await axp_editConfigFile(
                    'smb.conf',
                    display_text.value
                )
                if (response.status == 200) {
                    display_text_backup.value = display_text.value
                    compControl.edit_control.edit_mode = false
                    message.success('保存成功')
                    return true
                } else {
                    message.error('保存失败')
                    return false
                }
            } else {
                if (display_text_backup.value != display_text.value) {
                    return new Promise((resolve) => {
                        dialog.warning({
                            title: '警告',
                            content: '当前编辑的内容未保存，是否确认离开？',
                            positiveText: '离开',
                            negativeText: '取消',
                            onPositiveClick: () => {
                                display_text.value = display_text_backup.value
                                compControl.edit_control.edit_mode = false
                                resolve(true) // 用户选择离开，返回 true
                            },
                            onNegativeClick: () => {
                                resolve(false) // 用户选择取消，返回 false
                            }
                        })
                    })
                } else {
                    compControl.edit_control.edit_mode = false
                    return true
                }
            }
        }
    },
    com_modal_samba_sample: {
        show: false,
        data: `
[dept_share]
   # === 基础配置 ===
   comment = Department Shared Folder (Team Collaboration)
   path = /srv/samba/dept_share
   available = yes                   # 是否启用此共享（yes/no）
   browseable = yes                  # 是否在网络邻居中可见
   public = no                       # 是否允许匿名访问（覆盖全局设置）
   writable = yes                    # 是否允许写入（需与read only配合）

   # === 访问控制 ===
   valid users = @dept_team, @managers  # 允许访问的用户/组
   invalid users = root               # 明确禁止root用户访问
   read only = no                     # 全局读写权限（由write list细化）
   write list = @dept_team            # 允许写入的组
   admin users = @managers            # 管理员组拥有完全控制权
   guest ok = no                      # 禁止来宾访问（优先级高于public）

   # === 网络限制 ===
   hosts allow = 192.168.1.0/24       # 仅允许特定子网访问
   hosts deny = 0.0.0.0/0             # 拒绝其他所有IP（明确声明）

   # === 文件权限 ===
   create mask = 0770                 # 新文件权限（用户和组可读写）
   directory mask = 2770              # 新目录权限（+SGID保持组继承）
   force create mode = 0660           # 强制文件权限（忽略客户端请求）
   force directory mode = 2770        # 强制目录权限
   force group = dept_team            # 强制文件归属组

   # === 高级选项 ===
   hide dot files = yes               # 隐藏Unix隐藏文件（如.git/）
   veto files = /*.exe/*.bat/*.cmd/   # 禁止上传可执行文件
   delete veto files = yes            # 允许删除已存在的veto文件
   follow symlinks = no               # 禁止符号链接（防逃逸攻击）
   strict locking = auto              # 文件锁优化（避免冲突）

   # === 日志记录 ===
   logging = yes                      # 启用共享级日志
   log file = /var/log/samba/dept_share.log  # 独立日志文件
   max log size = 50                  # 日志大小限制（MB）
        `
    }
})

async function handleGetText() {
    const response = await axg_getConfigFile('smb.conf')
    display_text.value = response
    display_text_backup.value = response
}
defineExpose({
    refreshData: handleGetText,
    startEdit: compControl.edit_control.handleStartEdit,
    endEdit: compControl.edit_control.handleEndEdit
})

onMounted(() => {
    handleGetText()
})
</script>

<style lang="scss" scoped>
@use '@/components/framework/framework';
@use './quick-item.scss';
:deep(.tab-scroller) {
    $height: calc(framework.$framework_content_height - 42px - 1em);
    max-height: $height;
}
:deep(.n-tab-pane) {
    padding: 0.25rem 0 !important;
    //height: 300px;
}
:deep(.n-code__line-numbers) {
    background-color: #00a0000a;
    padding-right: 0.5rem;
}
:deep(.__code__) {
    border-radius: 0.375rem;
    width: 100%;
    padding: 0 0.5rem;
    background-color: #00000007;
}
.quick-start-bar {
    display: flex;
    align-items: center;
    background-color: #7fffd450;
    padding: 1px 0.5rem 2px 0.5rem;
}
</style>
